#!/usr/bin/python

import os
from glob import glob
import gobject
import gtk
import dbus
import dbus.service
import dbus.mainloop
from dbus.mainloop.glib import DBusGMainLoop
import pynotify
import time

ICON_DIR = os.path.expanduser('~/.gnome2/condition-alert-daemon/icons')

pynotify.init('Condition Alert Daemon')


def create_status_icon_for_id(id):
    matches = glob(os.path.join(ICON_DIR, id + ".*"))
    if len(matches) == 0:
	return gtk.status_icon_new_from_stock(gtk.STOCK_DIALOG_WARNING)
    else:
	return gtk.status_icon_new_from_file(matches[0])

def nullify(s):
    return None if s == "" else s
    


class Condition:
    def __init__(self, id):
	self.id = id
	self._icon = create_status_icon_for_id(id)
	self._bubble = None
    
    def alert(self, description):
	self._icon.set_tooltip(None if description == "" else description)
	self._icon.set_visible(True)

	if self._bubble is not None:
	    self._bubble.close()
	    
	self._bubble = pynotify.Notification(self.id, description)
	if self._icon.get_storage_type() != gtk.IMAGE_STOCK:
	    self._bubble.set_icon_from_pixbuf(self._icon.get_pixbuf())
	
	gobject.timeout_add(100, self._show_bubble)
	
    def _show_bubble(self):
	if self._bubble is not None:
	    if self._icon.is_embedded():
		self._bubble.attach_to_status_icon(self._icon)
	    self._bubble.show()
	
	return False
    
    def clear(self):
	self._icon.set_visible(False)
	if self._bubble is not None:
	    self._bubble.close()
	    self._bubble = None


class Conditions(dbus.service.Object):
    def __init__(self, *args):
	dbus.service.Object.__init__(self, *args)
	self.conditions = {}
    
    @dbus.service.method('com.highgateguild.Conditions', in_signature='ss')
    def alert(self, id, description):
	self._condition_for_id(id).alert(description)
    
    @dbus.service.method('com.highgateguild.Conditions', in_signature='s')
    def clear(self, identifier):
	if identifier in self.conditions.keys():
	    self.conditions.pop(identifier).clear()
    
    def _condition_for_id(self, id):
	if id in self.conditions.keys():
	    return self.conditions[id]
	else:
	    condition = Condition(id)
	    self.conditions[id] = condition
	    return condition

if not os.path.exists(ICON_DIR):
    os.makedirs(ICON_DIR)


DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
name = dbus.service.BusName("com.highgateguild.Conditions", bus)
conditions = Conditions(bus, "/com/highgateguild/Conditions")

try:
    gobject.MainLoop().run()
except KeyboardInterrupt:
    pass

